//
//  blogViewController.m
//  NewIMGII
//
//  Created by 步遴 李 on 12-5-1.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//



#import "blogViewController.h"
#import "PicViewController.h"
#import "AFNetworking.h"
#import "CommListViewController.h"
#import "CommEditViewController.h"
#import "WBSendView.h"

static NSUInteger const DefaultMaxConcurrentOperationCount = 4;
@implementation blogViewController
@synthesize picCount;
@synthesize blog = _blog;
@synthesize postContentView = _postContentView;
@synthesize operationQueue = _operationQueue;
@synthesize str = _str;
@synthesize commtent = _commtent;
@synthesize share = _share;
@synthesize commtentbar = _commtentbar;
@synthesize wbengine = _wbengine;

- (void)dealloc
{
    [self.postContentView release];
    [self.blog release];
    [self.operationQueue release];
    [super dealloc];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.hidesBottomBarWhenPushed = true;
        self.operationQueue = [[NSOperationQueue alloc] init];
    }
    
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}
#pragma mark -
#pragma mark UIWebViewDelegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
	NSString *picName = [[request URL] absoluteString];
	NSLog(@"picName is %@",picName);
	if ([picName hasPrefix:@"pic:"]) {
		[self showBigImage:[picName substringFromIndex:4]];
		return NO;
	}else {
		return YES;
	}
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{   
    self.picCount = 0;
    WBEngine *engine = [[WBEngine alloc] initWithAppKey:kImgIIAppKey appSecret:kImgIIAppSecret];
    [engine setRootViewController:self];
    [engine setDelegate:self];
    [engine setRedirectURI:@"http://"];
    [engine setIsUserExclusive:NO];
    self.wbengine = engine;
    
    UIBarButtonItem* navButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"网友评论"  
                                                                    style:UIBarButtonItemStylePlain 
                                                                    target:self 
                                                                    action:@selector(toCommentPage)];
                                      
                                      
                    
    if (self.blog.commentcount != nil) {
        NSString *comtitle = [[NSString alloc]initWithFormat:@"网友评论%@",self.blog.commentcount];
        navButtonItem.title = comtitle;
        [comtitle release];
    }


    [self.navigationItem setRightBarButtonItem:navButtonItem];
    [navButtonItem release];
    
    NSError *error = nil;
    if (self.blog.alread == NO) {        
        self.blog.alread = YES;
        NSArray *postUrl = [self.blog.imgurl componentsSeparatedByString:@", "];
        NSArray *showUrl = [self.blog.url componentsSeparatedByString:@", "];
            for (NSInteger i = 0; i < [postUrl count]; i++) {
            NSURL *imgurl = [NSURL URLWithString:[postUrl objectAtIndex:i]];
            NSURLRequest *imgrequest = [NSURLRequest requestWithURL:imgurl];
            AFImageRequestOperation *operation = [AFImageRequestOperation imageRequestOperationWithRequest:imgrequest success:^(UIImage *responseImage){
                NSData *data = UIImagePNGRepresentation(responseImage);
                [data writeToFile:[showUrl objectAtIndex:i] atomically:YES];
                self.picCount ++;
                if (self.picCount == ([postUrl count])) {
                    [self LoadPage];
                }
            }];
            [self.operationQueue addOperation:operation];
            [self.operationQueue setMaxConcurrentOperationCount:DefaultMaxConcurrentOperationCount];
            [self.blog.managedObjectContext save:&error];
        }
    } else
    {
        [self LoadPage];
    }
   
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}
- (void)toCommentPage{
    CommListViewController *clViewController =  [[CommListViewController alloc]initWithNibName:@"CommListViewController" bundle:nil];
    clViewController.blogid = self.blog.blogid;
    [self.navigationController pushViewController:clViewController animated:YES];
    [clViewController release];
}

- (void)viewDidUnload
{


    [super viewDidUnload];
    
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
-(void)showBigImage:(NSString *)imageName{
    self.navigationItem.title = @"显示图片";
    PicViewController *picviewController = [[PicViewController alloc]initWithNibName:@"PicViewController" bundle:nil];
    picviewController.picName = imageName;
    //NSLog(@"nv is %@",self.navigationController);
    [self.navigationController pushViewController:picviewController animated:YES];
    [picviewController release];
    return;
}

-(IBAction)EditComment:(id)sender{
    CommEditViewController* comEdit = [[CommEditViewController alloc]init];
    comEdit.blogid = self.blog.blogid;
    [self.navigationController pushViewController:comEdit animated:YES];
    return;
}
-(void)LoadPage{
    NSString *title = self.blog.title;
    NSString *desc = self.blog.context;
    NSString *thumbnail = self.blog.thumbnail;
    [self.postContentView setDelegate:self];
    resourcePath = [[NSBundle mainBundle] resourcePath];
    fpath = [[NSString alloc]initWithFormat:@"%@/default.html", resourcePath];
    self.str = [[NSString alloc]initWithContentsOfFile:fpath encoding:NSUTF8StringEncoding error:nil];
    [fpath release];
    if (title!= nil) {
        self.str = [self.str stringByReplacingOccurrencesOfString:@"!$title$!" withString:title];
    }
    
    desc = [NSString stringWithFormat:@".%@", desc];
    if (desc!= nil) {
        self.str = [self.str stringByReplacingOccurrencesOfString:@"!$text$!" withString:desc];
    }
    if (thumbnail!= nil) {
        self.str = [self.str stringByReplacingOccurrencesOfString:@"!$thumbnail$!" withString:thumbnail];
    }
    [self.postContentView loadHTMLString:self.str baseURL:nil];
    resourcePath = nil;
    fpath = nil;
    title = nil;
    desc = nil;
    thumbnail = nil;
}

-(IBAction)shareBlog:(id)sender
{
    if ([self.wbengine isLoggedIn] && ![self.wbengine isAuthorizeExpired])
    {
        WBSendView *sendView = [[WBSendView alloc] initWithAppKey:kImgIIAppKey appSecret:kImgIIAppSecret text:@"test" image:[UIImage imageNamed:@"bg.png"]];
        [sendView setDelegate:self];
        [sendView show:YES];
        [sendView release];
        return;
        
    }
    [self.wbengine logIn];
}

#pragma mark -
#pragma mark WBSDKDelegate
- (void)engineAlreadyLoggedIn:(WBEngine *)engine
{
    if ([engine isUserExclusive])
    {
        UIAlertView* alertView = [[UIAlertView alloc]initWithTitle:nil 
                                                           message:@"请先登出！" 
                                                          delegate:nil
                                                 cancelButtonTitle:@"确定" 
                                                 otherButtonTitles:nil];
        [alertView show];
        [alertView release];
    }
}
// Log in successfully.
- (void)engineDidLogIn:(WBEngine *)engine
{
    WBSendView *sendView = [[WBSendView alloc] initWithAppKey:kImgIIAppKey appSecret:kImgIIAppSecret text:@"test" image:[UIImage imageNamed:@"bg.png"]];
    [sendView setDelegate:self];
    [sendView show:YES];
    [sendView release];
}

- (void)sendViewDidFinishSending:(WBSendView *)view
{
    [view hide:YES];
    UIAlertView* alertView = [[UIAlertView alloc]initWithTitle:nil 
													   message:@"微博发送成功！" 
													  delegate:nil
											 cancelButtonTitle:@"确定" 
											 otherButtonTitles:nil];
	[alertView show];
	[alertView release];
}
- (void)sendView:(WBSendView *)view didFailWithError:(NSError *)error
{
    NSLog(@"didFailWithError: %@", error);
    [view hide:YES];
    UIAlertView* alertView = [[UIAlertView alloc]initWithTitle:nil 
													   message:@"微博发送失败！" 
													  delegate:nil
											 cancelButtonTitle:@"确定" 
											 otherButtonTitles:nil];
	[alertView show];
	[alertView release];
}

- (void)sendViewNotAuthorized:(WBSendView *)view
{
    [view hide:YES];
    
    [self dismissModalViewControllerAnimated:YES];
}

- (void)sendViewAuthorizeExpired:(WBSendView *)view
{
    [view hide:YES];
    
    [self dismissModalViewControllerAnimated:YES];
}
@end
